<template>
	<view>
		<!-- transparent -->
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="dialog-bg">
				<view class="close-btn" @click="close">
					<u-icon name="close"></u-icon>
				</view>
				<view class="title-box">
					<image class="logo" src="@/static/logo.png" mode="widthFix"></image>
					<text class="title">客满</text>
				</view>
				<text class="desc">请您授权头像、昵称、手机号信息，您授权的信息将受到严格保护，请放心使用。</text>
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image v-if="avatarUserUrl" class="avatar" :src="avatarUserUrl" mode="widthFix">
					</image>
					<image v-if="!avatarUserUrl" class="avatar" src="@/static/no-avatar.png" mode="widthFix">
					</image>
				</button>
				<input type="nickname" class="nickname-input" placeholder="请输入昵称" @change="onInputNameChange"
					maxlength="8" placeholder-style="color: #888888;" :value="nickName" />

				<button v-if="!phoneNumber.length" open-type="getPhoneNumber" class="custom-input-button"
					@getphonenumber="onGetPhoneNumber">获取手机号码</button>
				<input wx:else type="number" class="nickname-input" placeholder="请输入手机号码" @input="onInputPhoneChange"
					placeholder-style="color: #888888;" :value="phoneNumber" maxlength="11" disabled="{{true}}" />
				<button open-type="getUserInfo" @getuserinfo="handleUserInfo" class="auth-button"
					:disabled="disableCommitBtn">
					确认授权
				</button>
				<view v-if="showLoading" class="mask-content">
					<u-loading-icon></u-loading-icon>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		getUserInfo,
		updateUserInfo,
		uploadFile,
		getPhoneNumber
	} from '@/api/index.js'
	const avatarUserUrl = ref("")
	const nickName = ref("")
	const phoneNumber = ref("")
	const disableCommitBtn = ref(false)
	const showLoading = ref(false)
	const popup = ref()

	const close = () => {
		// 关闭弹窗
		popup.value.close()
	};
	const open = () => {
		// 打开弹窗
		popup.value.open()
	};

	const emits = defineEmits(['ok'])

	// 提交
	const handleUserInfo = (e) => {
		if (e?.detail?.userInfo) {
			setMineUserInfo()
		}
	};

	const handleCheckUserInfo = () => {
		console.log(avatarUserUrl.value);
		console.log(nickName.value);
		const isCheck = avatarUserUrl.value && nickName.value
		if (isCheck) {
			setMineUserInfo()
			popup.value.close()
		}
	}

	const getMineUserInfo = async () => {
		let res = await getUserInfo()
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			uni.setStorageSync("userInfo", res.data)
			emits('ok', true)
		}
	}


	const setMineUserInfo = async () => {
		let res = await updateUserInfo({
			headimg: avatarUserUrl.value,
			username: nickName.value,
			phone: phoneNumber.value
		})
		if (res?.code) {
			console.log("getUserInfo=>", res.data);
			getMineUserInfo()
		}
	}

	const onChooseAvatar = (e) => {
		const {
			avatarUrl
		} = e.detail
		const that = this;
		uploadAvatar(avatarUrl)
	};
	const uploadAvatar = (filePath) => {
		// 调用uni.uploadFile方法上传头像  
		// 全局默认的头信息（方便以后扩展）
		const defaultHeader = {}

		const token = uni.getStorageSync('token');
		defaultHeader['api-token'] = token
		defaultHeader['api-name'] = 'wxapp'
		uni.uploadFile({
			url: 'https://order.weiet.com/data/api.auth.center/upload', // 替换为你的服务器接口地址  
			filePath: filePath,
			header: defaultHeader,
			name: 'file', // 根据你的服务器接口要求设置  
			formData: {
				// 如果需要，可以在这里添加其他表单数据  
			},
			success: (res) => {
				// 处理上传成功的逻辑
				const data = JSON.parse(res.data || "")
				console.log('头像上传成功:', data.code);
				if (data.code) {
					avatarUserUrl.value = data.data.url
				} else {
					uni.showToast({
						icon: "none",
						title: data.info
					})
				}
			},
			fail: (err) => {
				// 处理上传失败的逻辑  
				console.error('头像上传失败:', err);
				uni.showToast({
					icon: "none",
					title: "头像上传失败"
				})
			}
		});
	}


	// 获取手机号
	const onGetPhoneNumber = async (e) => {
		// e.detail.encryptedData
		// e.detail.iv
		console.log('onGetPhoneNumber=' + JSON.stringify(e));
		var that = this;
		if (e.detail.errMsg === "getPhoneNumber:ok") {
			let res = await getPhoneNumber({
				token: uni.getStorageSync('token'),
				iv: e.detail.iv,
				encrypted: e.detail.encryptedData
			})
			if (res?.code) {
				console.log("onGetPhoneNumber=>", res.data);
				phoneNumber.value = res.data
			}
		}
	};

	const onInputNameChange = (e) => {
		nickName.value = e.detail.value
	}
	const onInputPhoneChange = (e) => {
		phoneNumber.value = e.detail.value
	}
	defineExpose({
		open,
		close,
	});
</script>

<style lang="scss" scoped>
	.dialog-bg {
		width: 100vw;
		min-height: 730rpx;
		height: 730rpx;
		background: #F7F7F7;
		border-radius: 32rpx 32rpx 0 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.close-btn {
		position: absolute;
		right: 0;
		top: 0;
		width: 128rpx;
		height: 128rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.title-box {
		width: 100%;
		margin-top: 40rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.logo {
		width: 48rpx;
		margin-left: 40rpx;
		height: 48rpx;
	}

	.title {
		margin-left: 16rpx;
		color: #333333;
		font-size: 32rpx;
	}

	.desc {
		margin: 20rpx 40rpx 0;
		color: #666666;
		font-size: 24rpx;
	}

	.avatar-wrapper {
		width: 128rpx;
		padding: 0;
		display: block;
		border-radius: 100%;
		border: 0;
		overflow: hidden;
		height: 128rpx;
		margin: 20rpx auto 0;
	}

	.avatar {
		width: 128rpx;
		height: 128rpx;
		display: block;
	}

	button::after {
		border: 0;
	}

	.nickname-input {
		width: calc(100% - 120rpx);
		height: 80rpx;
		padding: 0 30rpx;
		margin-top: 40rpx;
		background: #EEEEEE;
		color: #333333;
		border-radius: 80rpx;
		font-size: 28rpx;
	}

	.custom-input-button {
		width: calc(100% - 80rpx);
		height: 80rpx;
		margin-top: 40rpx;
		line-height: 80rpx;
		text-align: left;
		background: #EEEEEE;
		color: #888888;
		border-radius: 80rpx;
		font-size: 28rpx !important;
	}

	.auth-button {
		width: calc(100% - 80rpx);
		line-height: 80rpx;
		margin-top: 40rpx;
		font-size: 32rpx;
		border-radius: 80rpx;
		height: 80rpx;
		background: linear-gradient(315deg, #0ABCA4 0%, rgba(11, 195, 170, 0.8) 100%);
		color: #FFFFFF;
	}


	button[disabled] {
		color: #FFFFFF;
		background: linear-gradient(315deg, #0ABCA4 0%, rgba(11, 195, 170, 0.8) 100%);
		opacity: 0.6;
	}

	.mask-content {
		background: rgba(0, 0, 0, 0.3);
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		border-radius: 32rpx 32rpx 0 0;
	}

	.custom-loading {
		display: block;
		margin-top: 350rpx;
	}
</style>